<%@ page import="com.cy.model.UserMapRole" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="userRoleLevelItems" value="<%= UserMapRole.Level.toJson()%>"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CCRM管理平台</title>
    <link rel="stylesheet" href="${gPath}/styles/dpl-min.css" />
    <link rel="stylesheet" href="${gPath}/styles/bui-min.css" />
    <link rel="stylesheet" href="${gPath}/styles/main.css" />
</head>
<body>

<!--列表页-->
<div class="container">
    <form id="searchForm" class="form-panel">
    	<ul class="panel-content">
       		<li>
                <span>
                    <label>手机：</label><input type="text" class="control-text" name="user.mobile"/>
                </span>
                <span>
                    <label>昵称：</label><input type="text" class="control-text" name="user.nick_name"/>
                </span>
                <span>
                    <label>真实姓名：</label><input type="text" class="control-text" name="user.real_name"/>
                </span>
                <span>
                    <label>邮箱：</label><input type="text" class="control-text" name="user.email"/>
                </span>
                <span>
                    <label>等级：</label>
                    <select name="user.level">
                        <option value="">全部</option>
                        <option value="1">客户</option>
                        <option value="0">测试人员</option>
                    </select>
                </span>
                <span>
                	<label>状态：</label>
                    <select name="user.status">
                        <option value="">全部</option>
                        <option value="1">激活</option>
                        <option value="0">冻结</option>
                    </select>
                </span>
                <button type="button" id="btnSearch" class="button button-primary">搜索</button>
            </li>
        </ul>
    </form>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>
</div>

<!--表单页-->
<div id="ModelFormDialog" style="display: none">
    <form id="ModelForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">手机：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="user.mobile" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">昵称：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="user.nick_name" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">真实姓名：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="user.real_name" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">Email：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="user.email" />
            </div>
        </div>
        <div class="control-group" >
            <label class="control-label">角色：</label>
            <div class="controls checkbox" id="rolesDiv">
            </div>
            <input type="hidden" name="userRoles" id="userRoles"/>
            <input type="hidden" name="removeRoles" id="removeRoles"/>
        </div>
        <div class="control-group hide" id="levelDiv">
            <label class="control-label">工种：</label>
            <div class="controls">
                <select name="level" disabled="disabled">
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">公司：</label>
            <div class="controls">
                <select name="company_id">
                    <option value="">无</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">备注：</label>
            <div class="controls control-row4">
                <textarea name="user.remark" id="remark" class="input-large" data-tip="{text:'备注信息！'}"></textarea>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">状态：</label>
            <div class="controls">
                <select name="user.status" id="status">
                    <option value="0">冻结</option>
                    <option value="1">激活</option>
                </select>
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>


<div id="importMemberModal" class="is-hide ">
    <div class="text-center">
        <h1 class="pull-left span18">导入客户</h1>
        <p class="span18" style="margin-top: 5%">首先下载好EXCEL表格，再填写，再导入。 </p>
        <a target="_blank" href="http://cy-clmp.qiniudn.com/clmp导入客户模板V1.1.xlsx" class="button">下载EXCEL表格模板</a>
        <hr/>
    </div>
    <div class="text-center">
        <div id="J_Uploader"></div>
    </div>
    <div class="text-center importing" style="display: none;">
        <div class="tips tips-small tips-info span5 offset7">
            <span class="x-icon x-icon-small x-icon-info"><i class="icon icon-white icon-info"></i></span>
            <div class="tips-content">正在导入中，请稍后...</div>
        </div>
    </div>
</div>

<script type="text/javascript" src="${gPath}/scripts/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="${gPath}/scripts/bui.js"></script>
<script type="text/javascript" src="${gPath}/scripts/common/search.js"></script>
<script type="text/javascript">
    var URI = "${gPath}/clmp/user", MODULE='user';
    var thisUserRoleList=[];
    BUI.use(['common/search', 'bui/overlay', 'bui/form', 'bui/calendar'], function (Search, Overlay, Form, Calendar) {
        const USER_ROLE_LEVEL_ITEMS = ${userRoleLevelItems};
        var ele = $("select[name='level']");
        for (var k in USER_ROLE_LEVEL_ITEMS){
            ele.append("<option value='"+ k +"'>"+ USER_ROLE_LEVEL_ITEMS[k] +"</option>");
        }
        $.getJSON("${gPath}/item", {className: ["com.cy.model.Company","com.cy.model.RoleLabel"]}, function(result){
            ele = $("select[name='company_id']");
            for (var i in result.companyItems){
                var d = result.companyItems[i];
                ele.append("<option value='"+ d.id +"'>"+ d.name +"</option>");
            }
            ele = $("#rolesDiv");
            for (var i in result.roleLabelItems){
                var d = result.roleLabelItems[i];
                ele.append("<input type='checkbox' name='roles' "+ (d.level == 0 ? "onclick='showLevel(this)'" : "") +" value='"+d.role_id+"'/>"+d.role_name +"&nbsp;");
            }
        });

        var columns = [
            {dataIndex: 'company_id', visible: false},
            {dataIndex: 'user_id', visible: false},
            {title: '用户名', dataIndex: 'account', width: '8%'},
            {title: '手机', dataIndex: 'mobile', width: '8%'},
            {title: '昵称', dataIndex: 'nick_name', width: '10%'},
            {title: '真实姓名', dataIndex: 'real_name', width: '10%'},
            {title: '邮箱', dataIndex: 'email', width: '10%'},
            {title: '性别', dataIndex: 'sex', width: '5%',renderer: function (value, obj) {
                return value == 0 ? '女' : '男';
            }},
            {title: '级别', dataIndex: 'level', width: '3%'},
            {title: '注册时间', dataIndex: 'create_time', width: '10%'},
            {title: '公司', dataIndex: 'companyName', width: '10%',renderer:function(value, obj){
                return obj.company_id != null ? value : '';
            }},
            {title: '状态', dataIndex: 'status', width: '5%',renderer: function (value, obj) {
                return value == 0 ? '冻结':'激活';
            }},
            {title: '备注', dataIndex: 'remark', width: '10%'},
            {title: '操作', dataIndex: '', width: '8%', renderer: function (value, obj) {
                return '<shiro:hasPermission name="/clmp/user/*:post"><span class="grid-command btn-edit" title="编辑">编辑</span></shiro:hasPermission>';
            }}
        ];
        var store = Search.createStore(URI, {totalProperty: 'total'});
        var gridCfg = Search.createGridCfg(columns, {
            <shiro:hasPermission name="/res/_webApi/excel/user">
            tbar: {
                items: [
                    {text: '<i class="icon-upload"></i>批量导入', btnCls: 'button button-small', handler: function () {
                        importMemberModal.show();
                    }}
                ]
            },
            </shiro:hasPermission>
            emptyDataTpl : '<div style="padding: 20px" class="centered"><img src="${gPath}/img/nodata.png"><h2>好像还没有数据</h2></div>',
            plugins: [BUI.Grid.Plugins.CheckSelection]
        });

        var search = new Search({
            store: store,
            gridCfg: gridCfg
        });
        var grid = search.get('grid');

        //监听事件，删除一条记录
        grid.on('cellclick', function (ev) {
            var sender = $(ev.domTarget); //点击的Dom
            if (sender.hasClass('btn-edit')) {
                edit(ev.record);
            }
        });

        function edit(record) {
            $("input[name='roles']").removeAttr("checked");
            modelFormObject.clearFields();
            modelFormObject.set('action', URI + "/" + record.user_id);
            modelFormObject.set('method', "POST");
            for (var name in record) {
                modelFormObject.setFieldValue(MODULE+'.' + name, record[name]);
            }
            modelFormObject.setFieldValue("company_id", record.company_id);
            if (record.roleInfos){
                var roleInfos = record.roleInfos.split(",");
                var rolesDiv = $("#rolesDiv");
                for (var i in roleInfos){
                    var roleInfo = roleInfos[i].split("-");
                    var roleLevel = roleInfo[1];
                    var roleId = roleInfo[0];
                    var input = $("input[type='checkbox'][value='"+roleId+"']");
                    thisUserRoleList.push(roleId);
                    rolesDiv.find(input).attr("checked", true);
                    modelFormObject.setFieldValue("level", record.umrLevel);
                    if (roleLevel == '0'){
                        showLevel(input);
                    }
                }
            }
            modelFormDialog.show();
        }

        function findRemoveRoles(){
            var arr3= [];
            var updateRoles = [];
            $("input[name='roles']").each(function(){
                if($(this).is(':checked')){
                    updateRoles.push($(this).val());
                }
            });
            $("#userRoles").val(updateRoles.join("-"));

            for(var i=0;i<thisUserRoleList.length;i++){
                var stra=thisUserRoleList[i];
                var count=0;
                for(var j=0;j<updateRoles.length;j++){
                    var strb=updateRoles[j];
                    if(stra.toString()==strb.toString()){
                        count++;
                    }
                }
                if(count==0){//表示数组1的这个值没有重复的，放到返回列表中
                    arr3.push(stra);
                }
            }
            $("#removeRoles").val(arr3.join("-"));
        }

        var importMemberModal = new Overlay.Dialog({
            title: '批量导入',
            width: 800,
            height: 400,
            mask: false,
            buttons: [],
            contentId: 'importMemberModal'
        });

        var modelFormDialog = new Overlay.Dialog({
            title: '表单',
            width: 800,
            height: 650,
            mask: false,
            buttons: [],
            contentId: 'ModelFormDialog'
        });
        modelFormDialog.on("closed", function(){
            $("#levelDiv").hide();
        });

        var datepicker = new Calendar.DatePicker({
        	trigger:'.calendar',
            autoRender : true
        });

        var modelFormObject = new Form.HForm({
            srcNode: '#ModelForm',
            submitType: 'ajax',
            callback: function (data) {
                if (data.status === 1) {
                    BUI.Message.Alert('操作成功');
                    modelFormDialog.close();
                    search.load();
                } else {
                    BUI.Message.Alert('操作失败:' + data.msg);
                }
            }
        }).render();

        modelFormObject.on("beforesubmit",function(){
            findRemoveRoles();
            return true;
        });
        BUI.use('bui/uploader',function (Uploader) {
            var uploader = new Uploader.Uploader({
                render: '#J_Uploader',
                url: '${gPath}/res/_webApi/excel/user',
                queue: {
                    resultTpl:{
                        'success': '<div class="success">成功导入</div>',
                        'error': '<div class="error"><span class="uploader-error">{msg}</span></div>'
                    }
                },
                rules: {
                    //文的类型
                    ext: ['.xls,.xlsx,.xlsm','文件类型只能为{0}'],
                    //上传的最大个数
                    max: [5, '文件的最大个数不能超过{0}个'],
                    //文件大小的最小值,这个单位是kb
                    minSize: [1, '文件的大小不能小于{0}KB'],
                    //文件大小的最大值,单位也是kb
                    maxSize: [1024, '文件大小不能大于1M']
                },
                isSuccess: function(result){
                    $(".importing").hide();
                    if(result && result.code == 20001){
                        BUI.Message.Alert("成功导入"+result.count+'条数据;'+result.msg);
                        importMemberModal.hide();
                        search.load();
                        $(".action .bui-queue-item-del").target("click");
                        return true;
                    }
                    $(".action .bui-queue-item-del").target("click");
                    BUI.Message.Alert("系统繁忙");
                    return false;
                }
            }).render();

            uploader.on("start",function(e){
                $(".importing").show();
            })
        });
    });

    function showLevel(ele){
        if (ele instanceof HTMLElement){
            ele = $(ele);
        }
        if (ele.attr("checked")){
            $("select[name='level']").attr("disabled", false);
            $("#levelDiv").show();
        } else {
            $("select[name='level']").attr("disabled", true);
            $("#levelDiv").hide();
        }
    }
</script>
</body>
</html>